// pages/order/order-ok.js
const numeral = require("../../vendor/numeral/numeral.min")
const app = getApp()
Page({

    data: {
        hasAuth: true,
        isDoorChecked: true
    },

    onLoad: function(options) {
        options.cid = wx.getStorageSync('cid')
        this.setData(options)
        wx.showLoading({
            title: '加载中...',
        })
        this.loadData()
    },
    loadData() {
        let goods_type = this.data.goods_type
        let url = goods_type == 1 ? 'location/info' : 'supermarket/info'
        let data = Object.assign({
            community_id: this.data.cid
        }, app.okParam)
        Promise.all([
            app.http.get(url, { //baseInfo.delivery_info.delivery_style==2 邮寄
                data: {
                    cid: this.data.cid
                }
            }),
            app.http.get('order/check', {
                data
            }),
            app.http.get('user/default-address-info'),
        ]).then(res => {
            this.setData({
                baseInfo: goods_type == 1 ? res[0].data.data : Object.assign({
                    delivery_info: {
                        delivery_style: 1
                    },
					other_set:{
						send_home_price:-1
					}
                }, res[0].data),
                goodsList: res[1].data.list,
                totalPrice: res[1].data.priceTotal,
                phone: res[2].data.phone,
                name: res[2].data.name,
                address: res[2].data.address
            })
            wx.hideLoading()
            this.calculateTotal()
            wx.getStorage({
                key: 'receiving_address',
                success: res => {
                    this.setData({
                        receiving_address: res.data
                    })
                },
            })
        }).catch(err => {
            console.log(err)
        })
    },
    //是否送货上门
    checkboxDoor(evt) {
        this.setData({
            isDoorChecked: !this.data.isDoorChecked
        })
        this.calculateTotal()
    },
    /**
     * 修改数量
     */
    numClick(evt) {
        let dset = evt.currentTarget.dataset;
        let {
            index,
            step
        } = dset
        let goodsList = this.data.goodsList
        let quantity = parseInt(goodsList[index].quantity)
        quantity = quantity + parseInt(step)

        if (quantity < 1) {
            wx.showToast({
                icon: 'none',
                title: '宝贝不能再减少啦~',
            })
            return
        }
        if (quantity > goodsList[index].stock) {
            wx.showToast({
                icon: 'none',
                title: '库存不足啦~',
            })
            return
        }
        if (quantity > goodsList[index].max_buy_num && goodsList[index].max_buy_num != 0) {
            wx.showToast({
                icon: 'none',
                title: '宝贝已到达最大购买数~',
            })
            return
        }
        this.setData({
            [`goodsList[${index}].quantity`]: quantity,
        })
        this.calculateTotal()
    },
    /**
     * 计算商品总数
     */
    calculateTotal: function() {
        let goodsList = this.data.goodsList;
        let baseInfo = this.data.baseInfo
        let totalPrice = 0;
        let mail_differ = 0
        let abs_mail_differ = 0

        if (!goodsList) {
            return
        }
        for (let i = 0; i < goodsList.length; i++) {
            var good = goodsList[i];
            totalPrice += parseInt(good.quantity) * (good.mall_price - 0);
        }
        if (baseInfo.delivery_info.delivery_style == 2) {  //快递费
            mail_differ = parseFloat(baseInfo.delivery_info.info.min_money) - totalPrice
            abs_mail_differ = Math.abs(mail_differ)
        }
		if (baseInfo.other_set.send_home_price > 0 && this.data.isDoorChecked) { //上门费
			totalPrice += baseInfo.other_set.send_home_price
		}
        totalPrice = numeral(totalPrice).format("0,0.00")
        mail_differ = numeral(mail_differ).format("0,0.00")
        abs_mail_differ = numeral(abs_mail_differ).format("0,0.00")
        this.setData({
            totalPrice,
            mail_differ,
            abs_mail_differ
        })
    },
    // 收货地址
    selectAddress() {
        app.toPromise(wx.chooseAddress).then(res => {
            const receiving_address = {
                consignee_name: res.userName,
                phone: res.telNumber,
                province: res.provinceName,
                city: res.cityName,
                district: res.countyName,
                address: res.detailInfo,
                city_code: res.nationalCode
            }
            this.setData({
                receiving_address,
                noAddressTips: false
            })
            wx.setStorage({
                key: 'receiving_address',
                data: receiving_address,
            })
        }).catch(err => {
            console.log(err, 'xxxxxxxxx')
            this.openSetting()
        })
    },
    openSetting() {
        this.setData({
            hasAuth: true
        })
        app.toPromise(wx.getSetting).then(res => {
            if (res.authSetting['scope.address']) { //已经授权
                this.setData({
                    hasAuth: true
                })
            } else {
                this.setData({
                    hasAuth: false
                })
            }
        }).catch(err => {
            this.setData({
                hasAuth: true
            })
        })
    },
    bindinput(evt) {
        let value = evt.detail.value
        let key = evt.currentTarget.dataset.key
        this.setData({
            [`${key}`]: value
        })
    },

    /**
     * 支付
     */
    toPay() {
        let receiving_address = this.data.receiving_address
        let submit_type = this.data.baseInfo.delivery_info.delivery_style
        let user = wx.getStorageSync('user')
        if (this.data.paying || !user) {
            return
        }
        if (submit_type == 2 && !receiving_address) {
            this.setData({
                noAddressTips: true
            })
            return
        }
        if (submit_type != 2) {
            if (!this.data.name) {
                app.wxToast.warn('姓名不能为空')
                return
            }
            let reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
            if (!reg.test(this.data.phone)) {
                app.wxToast.warn('手机号不正确')
                return
            }
            if (!this.data.address) {
                app.wxToast.warn('地址不能为空')
                return
            }
            receiving_address = {
                consignee_name: this.data.name,
                phone: this.data.phone,
                address: this.data.address
            }
        }

        let list = this.data.goodsList
        let arr = []

        function f(obj, keys) {
            return keys.reduce((result, key) => {
                if (obj.hasOwnProperty(key)) {
                    result[key] = obj[key];
                }
                return result;
            }, {});
        }
        for (let i = 0; i < list.length; i++) {
            arr.push(f(list[i], ['goods_id', 'sku_id', 'quantity', 'id']))
        }


        let data = app.okParam
        data.goods_info = JSON.stringify(arr)
        data['cid'] = this.data.cid
        data.total_price = this.data.totalPrice
        data.is_send_home = this.data.baseInfo.other_set.send_home_price > 0 && this.data.isDoorChecked ? 1 : 0 //1= 送货上门 0 = 不送货上门
        data = Object.assign(receiving_address, data)
        // data.community_id = this.data.cid ? this.data.cid : 0
        // data.site_id = this.data.siteInfo ? this.data.siteInfo.id : 0
        // data.consignee_name = this.data.name
        // data.phone = this.data.phone
        // data.address = this.data.address
        this.setData({
            paying: true
        })
        wx.showLoading({
            title: '请稍等',
        })
        app.http.post('order/submit', {
            data
        }).then(res => {
            wx.hideLoading()
            if (res.data.status != 1) {
                wx.showModal({
                    title: '温馨提示',
                    content: res.data.msg,
                    showCancel: false,
                    confirmColor: '#ff5400',
                    success: res => {
                        wx.navigateBack({
                            delta: 1
                        })
                    }
                })
            }
            let jsPay = res.data.js
            let orderInfo = res.data.info
            if (orderInfo.pay_type == 2) { //余额支付
                wx.redirectTo({
                    url: '/pages/order/order-detail?order_id=' + orderInfo.order_id + '&order_type=' + data.type,
                })
                return
            }
            const obj = Object.assign(jsPay, {
                success: res => {
                    wx.redirectTo({
                        url: '/pages/order/order-detail?order_id=' + orderInfo.order_id + '&order_type=' + data.type,
                    })
                },
                fail: err => {
                    wx.showModal({
                        title: '温馨提示',
                        content: '未支付订单将在29分59秒后自动取消,请尽快支付',
                        showCancel: false,
                        confirmColor: '#ff5400',
                        success: res => {
                            if (res.confirm) {
                                wx.redirectTo({
                                    url: '/pages/order/order-detail?order_id=' + orderInfo.order_id + '&order_type=' + data.type,
                                })
                            }
                        }
                    })
                }
            });
            wx.requestPayment(obj)
            this.setData({
                paying: false
            })
        }).catch(err => {
            app.wxToast.error(err.message)
            this.setData({
                paying: false
            })
        })
    }
})